#include "client.h"
#include <iostream>
#include <thread>
#include <QDebug>
#include <QMutex>
#include <QImage>
#include <QDateTime>

QMutex mutex;
static QImage img;

#define SERVER_PORT 12580 // 服务器端口号

void myThreadFunction()
{
    char cmd[1024] = {0};
      while (1)
      {
          memset(cmd, 0, sizeof (cmd));
          int ret = read(Client::get()->sockfd, cmd, sizeof(cmd));
          if(ret <= 0)
          {
              close(Client::get()->sockfd);
              Client::get()->sockfd= -1;
              break;
          }

          qDebug() << cmd;
            mutex.lock();
            QDateTime currentDateTime = QDateTime::currentDateTime();
            QString time = currentDateTime.toString("yyyy-MM-dd_hh_mm_ss");

            QString path = QString("%1.jpg").arg(time);
            img.save(path);

            mutex.unlock();
            emit Client::get()->sigCar(cmd, time);
      }

}


Client::Client(QObject *parent) : QObject(parent)
{

}


Client::~Client()
{
    if(sockfd > 0)
        close(sockfd);
}

void Client::init()
{
    struct sockaddr_in server_addr;

    // 创建socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        perror("socket");
        exit(1);
    }

           //初始化服务的地址信息
    struct sockaddr_in  seraddr={0};
    seraddr.sin_family  = AF_INET; //使用IPv4协议
    seraddr.sin_port	= htons(12580);   //网络通信都使用大端格式
    seraddr.sin_addr.s_addr =  inet_addr(ip.c_str());  //32位的整形

    qDebug("%s\n",ip.c_str() );
    //链接服务器 struct sockaddr *
    int ret=::connect(sockfd,(struct sockaddr *)&seraddr,sizeof(seraddr));
    if(ret != 0)
    {
        perror("connect fail\n");
        return ;
    }

    printf("Connected to server\n");


    std::thread *myThread = new std::thread(myThreadFunction);
}



int Client::sendMsg(void *msg, int size)
{
    mutex.lock();
    if(sockfd >= 0)
    {
#define W 640
#define H 480
        img = QImage((unsigned char *)msg,W,H,QImage::Format_RGB888);
        int ret = ::send(sockfd, msg, size, 0);
        if (ret == -1)
        {
            perror("send");
            close(sockfd);
            sockfd = -1;
        }

    }
    mutex.unlock();
}
